#include "png8cropfx.h"
#include "imgsource.h"

#if defined PNG_READ_SUPPORTED && /* else nothing can be done */\
   defined PNG_READ_bKGD_SUPPORTED &&\
   defined PNG_READ_cHRM_SUPPORTED &&\
   defined PNG_READ_gAMA_SUPPORTED &&\
   defined PNG_READ_oFFs_SUPPORTED &&\
   defined PNG_READ_pCAL_SUPPORTED &&\
   defined PNG_READ_pHYs_SUPPORTED &&\
   defined PNG_READ_sBIT_SUPPORTED &&\
   defined PNG_READ_sCAL_SUPPORTED &&\
   defined PNG_READ_sRGB_SUPPORTED &&\
   defined PNG_READ_tEXt_SUPPORTED &&\
   defined PNG_READ_tIME_SUPPORTED &&\
   defined PNG_READ_zTXt_SUPPORTED &&\
   defined PNG_READ_tRNS_SUPPORTED &&\
   defined PNG_WRITE_SUPPORTED

namespace png8crop
{
	void imgsource::save(FILE* dest, size2d* crop_size, png_bytepp crop_rows)
	{
		png_structp png_ptr;
		png_infop info_ptr;
	
		png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
		info_ptr = png_create_info_struct(png_ptr);

		__try
		{
			if (setjmp(png_jmpbuf(png_ptr)))
			{
				throw ex_io(_T("Error while writing PNG file"));
			}

			png_init_io(png_ptr, dest);

			png_set_IHDR(png_ptr, info_ptr, crop_size->w, crop_size->h, 8, PNG_COLOR_TYPE_PALETTE,
				PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);

			png_set_PLTE(png_ptr, info_ptr, this->palette, this->num_palette);
			png_set_tRNS(png_ptr, info_ptr, this->trans_alpha, this->num_trans, NULL);


			png_set_rows(png_ptr, info_ptr, crop_rows);

			png_set_filter(png_ptr, 0, PNG_FILTER_VALUE_SUB);
			png_set_compression_level(png_ptr, 5);

			png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
		}
		__finally
		{
			png_destroy_write_struct(&png_ptr, &info_ptr);
		}
	}

	void imgsource::save(FILE* dest)
	{
		this->save(dest, &this->size, this->rows);
	}

	void imgsource::save(FILE* dest, crop *crop_info)
	{	
		png_bytepp crop_rows;

		__try
		{
			crop_rows= new png_bytep[crop_info->h];
		
			for(png_uint_32 i=0; i<crop_info->h; ++i)
			{
				crop_rows[i] = this->rows[i + crop_info->y] + crop_info->x;
			}

			this->save(dest, &crop_info->size, crop_rows);
		}
		__finally
		{
			delete[] crop_rows;
		}
	}
	
	imgsource::imgsource(void)
	{
	}

	imgsource::~imgsource(void)
	{
	}

	void imgsource::print_version_info(void)
	{
		fprintf(stderr, "\n Testing libpng version %s\n", PNG_LIBPNG_VER_STRING);
		fprintf(stderr, "   with zlib   version %s\n", ZLIB_VERSION);
		fprintf(stderr, "%s", png_get_copyright(NULL));
		/* Show the version of libpng used in building the library */
		fprintf(stderr, " library (%lu):%s",
			(unsigned long)png_access_version_number(),
			png_get_header_version(NULL));
	}
}


#endif

